import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import html2pdf from "html2pdf.js";
import type { ResumeFormData } from "./types";
import { nextTick } from "vue"; //

/**
 * 格式化日期为 YYYY.MM 格式
 * @param date 日期字符串
 * @returns 格式化后的日期字符串
 */
export const formatDate = (date: string): string => {
  return date ? dayjs(date).format("YYYY.MM") : "";
};

/**
 * 生成完整的简历HTML内容
 * @param formData 简历数据
 * @returns 生成的HTML字符串
 */
// generateResumeHTML
const generateResumeHTML = (formData: ResumeFormData): string => {
  return `
      <style>
      @media print {
        * {
          -webkit-print-color-adjust: exact !important;
          print-color-adjust: exact !important;
        }
        body {
          margin: 0 !important;
          padding: 0 !important;
        }
      }
    </style>
    <div style="width:210mm; margin:0 auto; padding:15mm; font-family:Arial; box-sizing:border-box;">
      <!-- 头部信息 -->
      <div style="text-align:center; margin-bottom:20px;">
        ${
          formData.avatar
            ? `
        <img src="${formData.avatar}" style="width:80px; height:80px; object-fit:cover; border-radius:50%; margin-bottom:10px;">
        `
            : ""
        }
        <h1 style="margin:0; font-size:24pt;">${formData.name || "姓名"}</h1>
        <h2 style="margin:0; color:#555; font-size:16pt;">${formData.title || "职位"}</h2>
      </div>

      <!-- 联系信息 -->
      <div style="display:flex; justify-content:center; flex-wrap:wrap; gap:15px; margin-bottom:20px;">
        ${formData.email ? `<div>📧 ${formData.email}</div>` : ""}
        ${formData.phone ? `<div>📱 ${formData.phone}</div>` : ""}
        ${formData.location ? `<div>📍 ${formData.location}</div>` : ""}
        ${formData.website ? `<div>🌐 ${formData.website}</div>` : ""}
      </div>

      <!-- 个人简介 -->
      ${
        formData.summary
          ? `
      <div style="margin-bottom:20px;">
        <h3 style="border-bottom:1px solid #eee; padding-bottom:5px;">个人简介</h3>
        <p style="line-height:1.6;">${formData.summary}</p>
      </div>
      `
          : ""
      }

      <!-- 教育经历 -->
      ${
        formData.education?.length
          ? `
      <div style="margin-bottom:20px;">
        <h3 style="border-bottom:1px solid #eee; padding-bottom:5px;">教育经历</h3>
        ${formData.education
          .map(
            (edu) => `
          <div style="margin-bottom:15px;">
            <div style="display:flex; justify-content:space-between;">
              <strong>${edu.school || ""}</strong>
              <span>${formatDate(edu.startDate)} - ${edu.endDate ? formatDate(edu.endDate) : "至今"}</span>
            </div>
            <div>${edu.degree || ""} ${edu.major ? `· ${edu.major}` : ""}</div>
            ${edu.description ? `<p style="margin-top:5px; line-height:1.5;">${edu.description}</p>` : ""}
          </div>
        `
          )
          .join("")}
      </div>
      `
          : ""
      }

      <!-- 工作经验 -->
      ${
        formData.experience?.length
          ? `
      <div style="margin-bottom:20px;">
        <h3 style="border-bottom:1px solid #eee; padding-bottom:5px;">工作经验</h3>
        ${formData.experience
          .map(
            (exp) => `
          <div style="margin-bottom:15px;">
            <div style="display:flex; justify-content:space-between;">
              <div>
                <strong>${exp.company || ""}</strong>
                <span>${exp.position ? ` · ${exp.position}` : ""}</span>
              </div>
              <span>${formatDate(exp.startDate)} - ${exp.endDate ? formatDate(exp.endDate) : "至今"}</span>
            </div>
            ${exp.description ? `<p style="margin-top:5px; line-height:1.5;">${exp.description}</p>` : ""}
          </div>
        `
          )
          .join("")}
      </div>
      `
          : ""
      }

      <!-- 项目经验 -->
      ${
        formData.projects?.length
          ? `
      <div style="margin-bottom:20px;">
        <h3 style="border-bottom:1px solid #eee; padding-bottom:5px;">项目经验</h3>
        ${formData.projects
          .map(
            (proj) => `
          <div style="margin-bottom:15px;">
            <div style="display:flex; justify-content:space-between;">
              <div>
                <strong>${proj.name || ""}</strong>
                <span>${proj.role ? ` · ${proj.role}` : ""}</span>
              </div>
              <span>${formatDate(proj.startDate)} - ${proj.endDate ? formatDate(proj.endDate) : "至今"}</span>
            </div>
            ${proj.technologies ? `<div style="margin:5px 0; color:#555;">技术栈: ${proj.technologies}</div>` : ""}
            ${proj.description ? `<p style="margin-top:5px; line-height:1.5;">${proj.description}</p>` : ""}
          </div>
        `
          )
          .join("")}
      </div>
      `
          : ""
      }

      <!-- 技能特长 -->
      ${
        formData.technicalSkills ||
        formData.softSkills ||
        formData.languages ||
        formData.certifications
          ? `
      <div style="margin-bottom:20px;">
        <h3 style="border-bottom:1px solid #eee; padding-bottom:5px;">技能特长</h3>
        ${
          formData.technicalSkills
            ? `
          <div style="margin-bottom:10px;">
            <strong>技术技能:</strong>
            <p style="margin-top:5px; line-height:1.5;">${formData.technicalSkills}</p>
          </div>
        `
            : ""
        }
        ${
          formData.softSkills
            ? `
          <div style="margin-bottom:10px;">
            <strong>软技能:</strong>
            <p style="margin-top:5px; line-height:1.5;">${formData.softSkills}</p>
          </div>
        `
            : ""
        }
        ${
          formData.languages
            ? `
          <div style="margin-bottom:10px;">
            <strong>语言能力:</strong>
            <p style="margin-top:5px; line-height:1.5;">${formData.languages}</p>
          </div>
        `
            : ""
        }
        ${
          formData.certifications
            ? `
          <div style="margin-bottom:10px;">
            <strong>证书认证:</strong>
            <p style="margin-top:5px; line-height:1.5;">${formData.certifications}</p>
          </div>
        `
            : ""
        }
      </div>
      `
          : ""
      }
    </div>
  `;
};

/**
 * 生成PDF简历
 * @param formData 简历数据
 */
export const generatePDF = async (formData: ResumeFormData): Promise<void> => {
  if (!formData.name) {
    //
    ElMessage.warning("请至少填写姓名后再生成简历"); //
    return; //
  } //

  await nextTick(); //

  const element = document.createElement("div");
  if (!element) return; //
  console.log("用户输入内容：", element); // 确认数据是否捕获
  element.innerHTML = generateResumeHTML(formData);

  element.style.cssText = `
  width: 210mm !important;
  min-height: 297mm !important;
  padding: 15mm !important;
  margin: 0 auto !important;
  background: white !important;
  box-sizing: border-box !important;
  font-family: Arial !important;
  `;
  document.body.appendChild(element);
  try {
    // 2. 生成PDF配置
    const options = {
      margin: -0.1, //10
      filename: `${formData.name || "我的简历"}.pdf`,
      image: { type: "jpeg", quality: 0.98 },
      html2canvas: {
        scale: 2,
        async: true,
        useCORS: true,
        allowTaint: true,
        logging: true,
        scrollX: 0,
        scrollY: 0,
        windowWidth: 794, // A4像素宽度
        onclone: (clonedDoc: Document | HTMLElement) => {
          clonedDoc
            .querySelector("div")
            ?.setAttribute(
              "style",
              "visibility: visible !important; position: static !important;"
            );
        },
      },
      jsPDF: {
        unit: "mm",
        format: "a4",
        orientation: "portrait",
      },
    };

    // 3. 生成并下载PDF
    await html2pdf().set(options).from(element).save();
    ElMessage.success("简历PDF生成成功");
  } catch (error) {
    console.error("PDF生成失败:", error);
    ElMessage.error(`PDF生成失败: ${(error as Error).message}`);
  } finally {
    if (document.body.contains(element)) {
      document.body.removeChild(element);
    }
  }
};
